import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { Empty, NavBar, SwipeCell,Notify, Flex, Button, Image, Typography, Checkbox, SubmitBar } from 'react-vant';
import './style.scss'
const App = () => {
  const [cart, setCart] = useState([]);

  const allPrice = cart.reduce((p, n) => {
    return p + n.count * n.price
  }, 0)
  const getCart = async () => {
    const resp = await axios.get('/api/cart/list');
    console.log(resp.data.data)
    setCart(resp.data.data)
  }
  const onClickRight = () => {
    setCart([])
  }
  const handleDelete= (id) => {
    axios.delete('/api/cart/list', { params: { id } }).then(() => {
      getCart()
    })
  }
  const onSubmit = () => {
    if(localStorage.getItem('token')) {

    } else {
      Notify.show({ type: "warning", message: '未登陆， 请登录' })
    }
  }
  useEffect(() => {
    getCart()
  }, [])
  if (cart.length > 0) {
    return <div>
      <NavBar
        title="购物车"
        rightText="清空"
        onClickRight={onClickRight}
      />
      {
        cart.map(v => {
          return <div key={v.id}>
            <SwipeCell
              rightAction={
                <Button onClick={() => handleDelete(v.id)} style={{ height: '100%' }} square type="danger">
                  删除
                </Button>
              }
            >
              <Flex className="demo-product-card" align="stretch">
                <Checkbox></Checkbox>
                <Image src={v.image} className="demo-product-card__img" />
                <Flex direction="column" justify="between" className="demo-product-card__content">
                  <div>
                    <Typography.Title level={5}>{v.title}</Typography.Title>
                    <Typography.Text type="secondary">{v.desc}</Typography.Text>
                  </div>
                  <Flex justify="between" align="center">
                    <Typography.Text strong size="lg">
                      ¥{v.price}
                    </Typography.Text>
                    <Typography.Text size="sm" type="secondary">
                      x{v.count}
                    </Typography.Text>
                  </Flex>
                </Flex>
              </Flex>
            </SwipeCell>
          </div>
        })
      }
      <SubmitBar price={allPrice * 100} buttonText="提交" onSubmit={onSubmit}/>
    </div>
  }

  return (
    <div>
      <NavBar
        title="购物车"
      />
      <Empty description="购物车没有数据"></Empty>
    </div>
  )
}

export default App